<?php
/**
 *
 * Author: TheSmile
 * Date: 2023/8/17 15:03
 * Email: <594652523@qq.com>
 */

namespace App\Admin\Extensions\Action;

use App\Imports\LatLngExcel;
use App\Models\Project;
use Encore\Admin\Actions\Action;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class LatLngImport extends Action
{
    /**
     * The form title.
     *
     * @var string
     */
    public $name = '导入经纬度';

    protected $selector = '.import-lat-lng';

    /**
     * Handle the form request.
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request)
    {
        $files     = $request->file();
        $projectId = $request->input('project_id');
        if (empty($projectId)) {
            return $this->response()->error('请选择需要导入的项目');
        }
        try {
            Excel::import(new LatLngExcel($projectId), $files['lat_lng_excel']);
            return $this->response()->success('导入成功')->refresh();
        } catch (\Exception $e) {
            return $this->response()->error('导入失败,错误-' . $e->getMessage());
        }

    }

    public function form()
    {
        $this->select('project_id', '项目')->options(function () {
            $query = Project::query();
//            if (!Admin::user()->isAdministrator()) {
//                $query->where('id', Admin::user()->club_id);
//            }
            return $query->pluck('name', 'id');
        })->required();
        $this->file('lat_lng_excel', '请选择文件')->required();
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-default import-lat-lng"><i class="fa fa-upload"></i>导入经纬度</a>
HTML;
    }

}
